// ==UserScript==
// @name         Chan Sankakucomplex recommendations auto loading
// @author       mcpan@foxmail.com
// @version      0.1
// @description  自动加载为你推荐的所有图片 省去翻页烦恼
// @match        https://chan.sankakucomplex.com/post/show/*
// @run-at       document-end
// ==/UserScript==

var homeurl = 'https://chan.sankakucomplex.com';

var recommended_next_url = null;
var recommended_next_page_is_loading = false;

var xmlhttp = new XMLHttpRequest();

function get_recommended_next_page()
{
	if (recommended_next_url &&
		!recommended_next_page_is_loading)
	{
		recommended_next_page_is_loading = true;

		xmlhttp.open('GET', recommended_next_url, true);
		xmlhttp.send();

		console.log('loading: ' + recommended_next_url);
	}
}

function get_recommended_next_url(contents)
{
	var matchs = contents.match(/\/post\/recommend\/\d+\?page=\d+.+>>>/g);
	recommended_next_url = matchs ? homeurl + matchs[0].replace(/'.+/g, '') : null;
}

function recommendations_append(contents)
{
	var matchs = contents.match(/<span\sclass=thumb.+/g);
	if (matchs)
	{
		var i, match_contents = '';
		for (i = 0; i < matchs.length; i++)
		{
			match_contents += matchs[i] + '\n';
		}

		document.getElementById("recommendations").innerHTML += '<br />' + match_contents;
	}

	get_recommended_next_url(contents);
}

function remove_recommendations_paginator()
{
	var recommendations = document.getElementById("recommendations"),
		recommendations_paginator = document.getElementById("recommendations-paginator");
	recommendations.removeChild(recommendations_paginator);
}

xmlhttp.onreadystatechange = function()
{
	if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
	{
		recommendations_append(xmlhttp.responseText);
		recommended_next_page_is_loading = false;
	}
}

window.onscroll = function()
{
	var diff = document.body.scrollHeight - document.body.scrollTop;
	// 这里是滚动条离底部的距离
	if (diff < 1600)
	{
		get_recommended_next_page();
	}
}

var recommended_next = document.getElementsByClassName('recommended-next')[0].innerHTML;
var matchs = recommended_next.match(/'\/post\/recommend\/\d+\?page=\d+/g);
if (matchs)
{
	recommended_next_url = matchs[0].replace(/'/g, homeurl);
}

// 去掉'为你推荐'的翻页链接
remove_recommendations_paginator();
